//
//  WCNCareRecordVC.m
//  WCN
//
//  Created by 杨鑫 on 15/6/16.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNCareRecordVC.h"
#import "WCNWoundDetailVC.h"
#import "WCNCareRecordDetailVC.h"
#import "WCNCareRecordAddVC.h"
#import "WCNCareSchemeListVC.h"
#import "WCNMulTextEditVC.h"
#import "WCNPatientAddVC.h"
//
#import "WCNCareRecordTCell.h"
#import "WCNCareRecordNoImgTCell.h"
#import "WCButton.h"
#import "WCNAddCareRecordSheetsPopView.h"
//
#import "MJRefresh.h"
//
#import "WCNPListFileDataStore.h"
#import "WCPopupLayerManager.h"
#import "WCNetworkAccessManager.h"
#import "WCImageManager.h"
#import "WCCoreDataStore.h"
#import "WCDefaultManager.h"
//
#import "NSObject+Utilities.h"
#import "UINavigationItem+Offset.h"
#import "NSString+Utilities.h"
#import "NSDate+Utilities.h"
//
#import "Macros.h"
#import "Constants.h"
//
#import <objc/runtime.h>

#import "Masonry.h"
#import "JCAlertView.h"
#import "WCNCareRecordCommentListVC.h"
#import "WoundRecord.h"

static NSString *cellId1 = @"WCNCareRecordTCell";
static NSString *cellId2 = @"WCNCareRecordNoImgTCell";

#warning 用于UIAlertView关联引用
static char kAlertInfoObjectKey;

@interface WCNCareRecordVC ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate,UIGestureRecognizerDelegate,UIActionSheetDelegate>

@property (strong, nonatomic) Account *account;
@property (nonatomic) WCNCareRecordVCMode mode;
@property (strong, nonatomic) id patient;

// 长按的cell
@property (strong, nonatomic) NSIndexPath *longPressIndex;

@property(nonatomic, strong) UITableView *tableView;
@property (weak, nonatomic) UIControl *maskView;
@property (weak, nonatomic) WCNAddCareRecordSheetsPopView *popView;
@property (weak, nonatomic) UIButton *taskButton;

@property (strong, nonatomic) NSString *filePath;
@property (strong, nonatomic) NSArray *detail;


//当前伤口
@property (strong, nonatomic) WoundRecord *wound;

//今日推荐
@property (strong, nonatomic) NSMutableArray *tasksToday;

//
@property (nonatomic) int count;
@property (nonatomic) BOOL forceRefresh;
//上拉加载的页面
@property (nonatomic, assign) NSInteger page;
//最大页数
@property (nonatomic, assign) NSInteger totalPage;
@property (weak, nonatomic) MBProgressHUD *hud;
@property (nonatomic, strong) UIButton *footerBtn;

@end
#warning 注意
/// 这个控制器 被两个 模块 共用 (患者  和 案列 模块 都可进入,案列进去的时候 不加载伤口 且是不可编辑状态, 患者进去的时候是可以编辑状态 且数据源 需要加载 伤口和护理两种cell)
@implementation WCNCareRecordVC

- (instancetype)initWithTitle:(id)patient mode:(WCNCareRecordVCMode)mode wound:(id)wound {

    _wound = wound;
    return [self initWithTitle:patient mode:mode];
    
}

- (instancetype)initWithTitle:(id)patient mode:(WCNCareRecordVCMode)mode
{
    self = [super init];
    if (self) {
        //
        _account = [[WCDefaultManager shareMg] account];
        _patient = patient;
        
        //_mode = mode;
        //根据护理状态 设置模式
        NSString *nursingStatus = [patient valueForKey:@"nursingStatus"];
        //只有在 患者 是监护时才可编辑
        if ([@"MONITORING" isEqualToString:nursingStatus]) {
            _mode = WCNCareRecordVCModeEdit;
        } else if ([@"NURSING" isEqualToString:nursingStatus]) {
            _mode = WCNCareRecordVCModeEdit;
        } else {
            _mode = WCNCareRecordVCModeScan;
        }
       
        WCNPListFileDataStore *plistStore = [WCNPListFileDataStore shareStore];
        //plist文件路径(以患者id 文件名)
        _filePath = [plistStore careRecordPath:[NSString stringWithFormat:@"care%@.plist", [patient valueForKey:@"stringId"]]];
        if ([plistStore hasFile:_filePath]) {
            //先从本地 读取plist文件(护理记录 和)
            //WOUND_ADD_RECORD
            
            _detail = [plistStore readArrayFromFile:_filePath];
        } else {
            _detail = [NSArray array];
        }
        _count = 0;
        _forceRefresh = YES;
        _page = 1;
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.titleView = [self titleView];
    defineWeakSelf;
   // 编辑模式 才有编辑 按钮
    if (self.mode == WCNCareRecordVCModeEdit) {
        WCButton *addRecordBtn = [WCButton wcButtonWithType:WCButtonTypeAdd];
        addRecordBtn.frame = CGRectMake(40, 0, 40, 30);
        [addRecordBtn addTarget:self action:@selector(addRecordBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        WCButton *choiceCase = [WCButton wcButtonWithType:WCButtonTypeList];
        [choiceCase addTarget:self action:@selector(choiceCase:) forControlEvents:UIControlEventTouchUpInside];
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
        [view addSubview:choiceCase];
        [view addSubview:addRecordBtn];
    
        [self.navigationItem addRightBarButtonItem:view];
    }
        //监听是否有 刷新通知
        [[NSNotificationCenter defaultCenter] addObserverForName:CareRecordsRefreshNotification object:nil queue:nil usingBlock:^(NSNotification *note){
            weakSelf.forceRefresh = YES;
            //视图在当前窗口  强制刷新  ---
            if (weakSelf.view.window) {
                [weakSelf refreshStepOne:YES];
            }
        }];
    
    //self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 10)];
    [self.tableView registerNib:[UINib nibWithNibName:cellId1 bundle:nil] forCellReuseIdentifier:cellId1];
    [self.tableView registerNib:[UINib nibWithNibName:cellId2 bundle:nil] forCellReuseIdentifier:cellId2];
    if (_is_comeFromParent) {
        [self.tableView setFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 40)];
    }
    // 添加下拉刷新头部控件
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        weakSelf.page = 1;
        //请求加载数据
        [weakSelf getRecordListFromWeb];
    } dateKey:@"WCNCareRecordVCTableView"];
    
    [self.tableView addLegendFooterWithRefreshingBlock:^{
         weakSelf.page++;
        //请求加载数据
        [weakSelf getRecordListFromWeb];
    }];
    [self.view addSubview:self.footerBtn];
    
    
    
    
    //    wechat_share
    
 

}

- (void)setIs_comeFromParent:(BOOL)is_comeFromParent {

    _is_comeFromParent = is_comeFromParent;
   
}


- (UIButton *)footerBtn{
    if (!_footerBtn) {
        _footerBtn =[UIButton buttonWithType:UIButtonTypeSystem];
        _footerBtn.frame =CGRectMake(30, kScreenHeight -35-65-40, kScreenWidth -60, 35);
        [_footerBtn setTitle:@"添加护理记录" forState:UIControlStateNormal];
        [_footerBtn setBackgroundColor:HexRGB_WSJ(84, 130, 255)];
        _footerBtn.layer.cornerRadius = 5;
        _footerBtn.layer.masksToBounds= YES;
        [_footerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_footerBtn addTarget:self action:@selector(addCareRecord) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _footerBtn;
    
}

- (void)addCareRecord {
    
        WCNCareRecordAddVC *vc = [[WCNCareRecordAddVC alloc] initWithPatient:self.patient wound:self.wound type:WCNCareRecordAddVCTypeAdd];
    if (self.navigationController) {
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        
        [self.delegateNav() pushViewController:vc animated:YES];
        
    }
}



- (UITableView *)tableView {

    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 36) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = kAppBg;
        _tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_tableView];
        UILongPressGestureRecognizer *gestureLongPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(gestureLongPress:)];
        gestureLongPress.minimumPressDuration = 1;
        [_tableView addGestureRecognizer:gestureLongPress];
    }
    return _tableView;

}


//每次控制器的view即将显示的时候 强制刷新
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.forceRefresh) {
        [self refreshStepOne:self.forceRefresh];
    }else {
        [self getRecordListFromWeb];
    }
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"--------------WCNCareRecordAddVC-------------------");

}

/**
 *  获取 上传失败并缓存在本地的护理记录，以及上传成功之后缓存在本地的护理记录， 然后根据上传时间将两者进行排序
 */
- (void)loadLocalCache
{
    WCNPListFileDataStore *plistStore = [WCNPListFileDataStore shareStore];
    
    //上次 编辑后未上传 保存在本地的 路径 (护士 a 病人b 的)
    NSString *plistFileName = [NSString stringWithFormat:@"Nurse%@_Patient%@.plist", _account.stringId, [self.patient valueForKey:@"stringId"]];
    NSString *path = [plistStore careUploadPath:plistFileName];
    if ([plistStore hasFile:path]) { //有未上传 的缓存
        NSMutableArray *newDetail = [NSMutableArray array];
        NSMutableArray *careArray = [[plistStore readArrayFromFile:path] mutableCopy];
        //移除已经添加过的本地（未上传的）数据，防止重复
        NSMutableArray *muarr = [NSMutableArray arrayWithArray:self.detail];
        for (NSDictionary *item in careArray) {
            for (NSDictionary *obj in self.detail) {
                if ([obj[@"uploadTime"] isEqualToString:item[@"uploadTime"]]) {
                    [muarr removeObject:obj];
                }
            }
        }
        _detail = [muarr copy];
        if (self.detail.count == 0) {
            _detail = [careArray mutableCopy];
            return;
        }
        int j = 0;
//        根据 新增时间 排序
        for (NSDictionary *item in careArray) {
            
                NSDate *itemCreateDate = [NSDate dateWithString:item[@"uploadTime"] byFormat:@"yyyy-MM-dd HH:mm:ss"];
                for (; j<self.detail.count; j++) {
                    
                    NSDictionary *detailItem = self.detail[j];
                    NSDate *detailItemCreateDate = [NSDate dateWithString:detailItem[@"uploadTime"] byFormat:@"yyyy-MM-dd HH:mm:ss"];
                    if ([detailItemCreateDate isEarlierThanDate:itemCreateDate]) {
                        [newDetail addObject:item];
                        break;
                    } else {
                        [newDetail addObject:detailItem];
                    }
                }
            
        }
        for (; j<self.detail.count; j++) {
            [newDetail addObject:self.detail[j]];
        }
        self.detail = newDetail;
    }
}

//记录列表
- (void)getRecordListFromWeb {

    defineWeakSelf;
    Account *account = [[WCDefaultManager shareMg] account];
    NSString *patientId = [self.patient valueForKey:@"stringId"];
    //护理记录列表
    NSDictionary *params = @{@"recordId":patientId, @"type":@"WOUND_NURSING_RECORD", @"page":@(self.page), @"rows":@10, @"bodyPartCode":self.wound.bodyPartCode, @"nurseId":account.stringId};
    //获取伤口记录列表
    MBProgressHUD *hud;
    if (!self.hud) {
        hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
        self.hud = hud;
    }
    self.count++;
    [[WCNetworkAccessManager sharedMg] GET:kGetWoundNursingRecord parameters:params success:^(NSDictionary *result){
    
        NSMutableArray *arr = [NSMutableArray arrayWithArray:result[@"data"][@"result"]];
     
        //判断是上拉刷新？  还是下拉加载？
        if (weakSelf.page > 1) {
            NSMutableArray *muArr = [NSMutableArray arrayWithArray:weakSelf.detail];
            [muArr addObjectsFromArray:arr];
            weakSelf.detail = [muArr copy];
            weakSelf.totalPage = [[result[@"data"] objectForKey:@"totalPage"] integerValue];
        }else {
            weakSelf.detail = arr;
        }
        //存到本地 plist文件中----------------------------------------
        [[WCNPListFileDataStore shareStore] saveData:weakSelf.detail toFile:weakSelf.filePath success:nil];
        
    } failure:nil netError:nil always:^{
        
        //加载本地缓存
        [weakSelf loadLocalCache];
        [weakSelf.tableView reloadData];
        if (weakSelf.page > 1) {
            [weakSelf.tableView.footer endRefreshing];
            if (weakSelf.page - 1 == weakSelf.totalPage) {
                
                [weakSelf.tableView.footer noticeNoMoreData];
            }
        }else {
            [weakSelf.tableView.header endRefreshing];
            [weakSelf.tableView.footer resetNoMoreData];
        }
        [weakSelf refreshStepTwo];
        
    }];
}


- (void)refreshStepOne:(BOOL)force
{
    MBProgressHUD *hud;
    defineWeakSelf;
    NSString *patientId = [self.patient valueForKey:@"stringId"];
    
    //护理记录列表
    NSString *urlStrng1 = [NSString stringWithFormat:@"nursing/task/list/%@", patientId];
    if (force || [[WCNetworkAccessManager sharedMg] timeSinceLastUrl:urlStrng1] > kUrlCD/10) {
        [self getRecordListFromWeb];

    }
    
    //可编辑状态下
    if (self.mode == WCNCareRecordVCModeEdit) {
        //更新该病人的护理案例
        //案例列表(护理方案设置列表)
        NSString *urlStrng2 = [NSString stringWithFormat:@"nursing/case/list/%@", patientId];
        if (force || [[WCNetworkAccessManager sharedMg] timeSinceLastUrl:urlStrng2] > kUrlCD/10) {
            if (!self.hud) {
                hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
                self.hud = hud;
            }
            self.count++;
            NSDictionary *params = @{@"status": @"IN_PROGRESS"};
            [[WCNetworkAccessManager sharedMg] POST:urlStrng2 parameters:params success:^(NSDictionary *result){
                [[WCCoreDataStore shareStore] createPatientSchemes:result[@"data"] withRecord:patientId];
            } failure:nil netError:nil always:^{
                [weakSelf refreshStepTwo];
            }];
        }
        
    }
    
    self.forceRefresh = NO;
}

- (void)refreshStepTwo
{
    self.count--;
    if (self.count > 0) {
        return;
    }
    
    self.count = 0;
    [self.hud hide:YES afterDelay:0.5];
    
    if (self.mode == WCNCareRecordVCModeScan) {
        return;
    }
    defineWeakSelf;
    NSArray *schemes = [[WCCoreDataStore shareStore] getPatientSchemes:[self.patient valueForKey:@"stringId"]];
    for (PatientScheme *scheme in schemes) {
        //更新每个护理案例
        NSString *fileName = [NSString stringWithFormat:@"case%d.plist", scheme.templateCaseId];
        NSString *filePath = [[WCNPListFileDataStore shareStore] careTemplatePath:fileName];
        NSString *careCaseUrl = [NSString stringWithFormat:@"template/nursing/task/list/%d", scheme.templateCaseId];
        if ([[WCNetworkAccessManager sharedMg] timeSinceLastUrl:careCaseUrl] > kUrlCD/10) {
            self.count++;
            [[WCNetworkAccessManager sharedMg] GET:careCaseUrl parameters:nil success:^(NSDictionary *result){
                [[WCNPListFileDataStore shareStore] saveCareRecords:result[@"data"] toFile:filePath success:^{
                    [weakSelf showTodayTaskView];
                }];
            } failure:nil netError:nil always:nil];
        }
    }
    
    if (self.count == 0) {
        [self showTodayTaskView];
    }
    
}

#pragma mark - 重新上传未上传成功的图片,
//上传至图片服务器，成功后返回图片在服务器上的url数组

- (void)uploadCacheCareAtIndexPath:(NSIndexPath *)indexPath
{
    
    __block NSArray *temArray;
    __block NSInteger isFailue = 0;;
//        NSDictionary *timeItem = self.detail[indexPath.row];
    WCNCareRecordTCell *imgcell = (WCNCareRecordTCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    //获取未上传成功的图片
    NSArray *imgs;
    if ([imgcell isKindOfClass:[WCNCareRecordTCell class]]) {
        
        imgs=[imgcell images];
    }
    if (imgs.count==0) {
        [self uploadCacheCareStep2:nil withIndexPath:indexPath];
        return;
    }
    defineWeakSelf;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        temArray = imgs;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [JCAlertView showTwoButtonsWithTitle:@"提示" Message:@"是否确认上传图片?" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"否" Click:^{
                
            } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"确认" Click:^{
             
              
        
                __weak MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];
                weakSelf.hud = hud;
                //    hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
                hud.animationType = MBProgressHUDAnimationZoomIn;
                //    hud.labelText = @"正在下载...";
                
                //------------------------------------
                __block NSInteger sucessTag = 0;
                NSMutableArray *namesArray =[NSMutableArray array];
                hud.labelText = [NSString stringWithFormat:@"1/%i",temArray.count];
                
                //------------------------------------
               
                for (int i =0; i<temArray.count; i++) {
                    [[WCImageManager sharedMg] uploadImage:@[temArray[i]] multi:NO  progress:^(NSProgress *progress) {
                        
//                      hud.pr   progress.fractionCompleted
                        
                    } success:^(NSDictionary *result){
                        //                    [hud hide:YES];
                        sucessTag ++;
                        
                        
                        hud.labelText = [NSString stringWithFormat:@"%d/%i",sucessTag,temArray.count];
                        

                        NSString * imageId =result[@"data"][@"name"];
                        if (imageId) {
                            [namesArray addObject:imageId];
                        }
                        //                        NSArray *imageInfos = result[@"data"];
                        //                        NSMutableArray *names = [NSMutableArray array];
                        //                        for (NSDictionary *imageInfo in imageInfos) {
                        //                            [names raddObject:imageInfo[@"name"]];
                        //                        }
                        if (sucessTag ==temArray.count &&isFailue==0) {
                            [weakSelf uploadCacheCareStep2:namesArray withIndexPath:indexPath];

                        }
                        
                    } failure:^(NSString *msg){
                        
                        if (isFailue==0) {
                            [JCAlertView showOneButtonWithTitle:@"提示" Message:@"上传失败" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"知道了" Click:nil];
                            isFailue =1;
                        }
                        
                        //                                            [hud hide:YES];
                     
                        [hud hide:YES];
                      
                    }];
                    
                }

            }];
            
            
            
        });
        
    });
}

/**
 *  把图片url 上传至服务器，上传成功之后刷新页面
 *
 *  @param imageNames 存放url的数组
 *  @param indexPath  选择重新上传的护理记录
 */
- (void)uploadCacheCareStep2:(NSArray *)imageNames withIndexPath:(NSIndexPath *)indexPath
{
    defineWeakSelf;
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
    NSDictionary *timeItem = self.detail[indexPath.row];
    NSMutableDictionary *careData = [timeItem mutableCopy];
    [careData removeObjectForKey:@"index"];
    careData[@"images"] = imageNames?imageNames:@[];
    NSDictionary *params = @{@"recordId":[self.patient valueForKey:@"stringId"], @"detail":[NSString dataToJsonString:careData]};
    [[WCNetworkAccessManager sharedMg] POST:@"nursing/task/add" parameters:params success:^(NSDictionary *result){
        [weakSelf deleteLocalCareRecordByIndex:indexPath];
        [weakSelf refreshStepOne:YES];
    } failure:nil netError:nil always:^{
        [hud hide:YES];
    }];
}

/**
 *  删除未上传成功的记录
 *
 *  @param indexPath 记录的位置
 */

- (void)deleteLocalCareRecordByIndex:(NSIndexPath *)indexPath
{
    NSDictionary *timeItem = self.detail[indexPath.row];
    
    WCNPListFileDataStore *plistStore = [WCNPListFileDataStore shareStore];
    WCImageManager *imageManager = [WCImageManager sharedMg];
    //删除本地缓存的图片
    NSArray *images = timeItem[@"images"];
    for (NSString *imageLocalName in images) {
        [imageManager deleteImageAfterUpload:imageLocalName];
    }
    //删除本地缓存数据
    NSString *plistFileName = [NSString stringWithFormat:@"Nurse%@_Patient%@.plist", self.account.stringId, [self.patient valueForKey:@"stringId"]];
    NSString *path = [plistStore careUploadPath:plistFileName];
    if ([plistStore hasFile:path]) {
        NSUInteger index = [timeItem[@"index"] integerValue];
        NSMutableArray *careArray = [[plistStore readArrayFromFile:path] mutableCopy];
        [careArray removeObjectAtIndex:index];
        for (int i = 0; i < careArray.count; i++) {
            NSMutableDictionary *muCareCacheItem = [NSMutableDictionary dictionaryWithDictionary:careArray[i]];
            [muCareCacheItem setValue:[NSNumber numberWithInt:i] forKey:@"index"];
            [careArray replaceObjectAtIndex:i withObject:muCareCacheItem];
        }
        if (careArray.count == 0) {
            [plistStore deleteCacheCaresAfterUpload:path];
        } else {
            [plistStore saveData:careArray toFile:path success:nil];
        }
    }
    NSMutableArray *muDetail = [NSMutableArray arrayWithArray:self.detail];
    [muDetail removeObjectAtIndex:indexPath.row];
    self.detail = [muDetail copy];
}

/**
 *  已经上传成功，且缓存再本地的数据 根据index将选中的数据删除
 *
 *  @param indexPath 选中的位置
 */

- (void)deleteLocalCacheByIndex:(NSIndexPath *)indexPath
{
    NSMutableArray *muDetail = [NSMutableArray arrayWithArray:self.detail];
    [muDetail removeObjectAtIndex:indexPath.row];
    self.detail = [muDetail copy];
    //存到本地 plist文件中----------------------------------------
    [[WCNPListFileDataStore shareStore] saveData:self.detail toFile:self.filePath success:nil];
    [self.tableView reloadData];
}



#pragma mark - 今日推荐

- (void)showTodayTaskView
{
    self.count--;
    if (self.count > 0) {
        return;
    }
    
    self.count = 0;
    
    if (self.mode == WCNCareRecordVCModeScan) {
        return;
    }
    
    if (self.taskButton) {
        [self.taskButton removeFromSuperview];
    }
    
    if (!self.tasksToday) {
        self.tasksToday = [NSMutableArray array];
    } else {
        [self.tasksToday removeAllObjects];
    }
    
    NSArray *schemes = [[WCCoreDataStore shareStore] getPatientSchemes:[self.patient valueForKey:@"stringId"]];
    for (PatientScheme *scheme in schemes) {
        NSString *fileName = [NSString stringWithFormat:@"case%d.plist", scheme.templateCaseId];
        NSString *filePath = [[WCNPListFileDataStore shareStore] careTemplatePath:fileName];
        NSArray *records = [[WCNPListFileDataStore shareStore] readArrayFromFile:filePath];
        
        NSDate *currentDate = [NSDate date];
        NSDate *oldDate = [NSDate dateWithString:scheme.startDate byFormat:@"yyyy-MM-dd"];
        int targetDay = scheme.startDay + (int)[currentDate daysAfterDate:oldDate];
        
        //检查是否已经添加过任务
        BOOL needAddTask = YES;
        for (NSDictionary *careItem in self.detail) {
            if ([scheme.bodyPartCode isEqualToString:careItem[@"bodyPartCode"]] && targetDay == [careItem[@"targetDay"] intValue]) {
                needAddTask = NO;
                break;
            }
        }
        
        if (!needAddTask) {
            continue;
        }
        
        //判断护理方案是否已经过期
        NSArray *lastRecord = [records lastObject];
        if (lastRecord) {
            if ([lastRecord[0][@"targetDay"] intValue] < targetDay) {
                //过期删除护理方案
                NSMutableDictionary *params = [[NSObject getObjectData:scheme] mutableCopy];
                params[@"id"] = scheme.stringId;
                params[@"status"] = @"COMPLETED";
                params[@"updateBy"] = self.account.stringId;
                [params removeObjectForKey:@"stringId"];
                [params removeObjectForKey:@"startDate"];
                
                [[WCNetworkAccessManager sharedMg] POST:@"nursing/case/update" parameters:params success:^(NSDictionary *result){
                    scheme.status = @"COMPLETED";
                } failure:nil netError:nil always:nil];
            } else {
                for (NSArray *recordDay in records) {
                    if ([recordDay[0][@"targetDay"] intValue] == targetDay) {
                        for (NSDictionary *recordItem in recordDay) {
                            NSMutableDictionary *task = [NSMutableDictionary dictionaryWithDictionary:recordItem];
                            [task setValue:nil forKey:@"id"];
                            [task setValue:scheme.bodyPartCode forKey:@"bodyPartCode"];
                            [task setValue:scheme.bodyPartName forKey:@"bodyPartName"];
                            [task setValue:scheme.templateCaseName forKey:@"templateCaseName"];
                            [task setValue:nil forKey:@"images"];
                            [self.tasksToday addObject:task];
                        }
                        break;
                    }
                }
            }
        }
    }
    defineWeakSelf;
    
    if (self.tasksToday.count > 0) {
        NSMutableDictionary *task = self.tasksToday[0];
        
        UIButton *taskButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.taskButton = taskButton;
        taskButton.frame = CGRectMake(0, -40, kScreenWidth, 40);
        taskButton.backgroundColor = HexRGBAlpha(0x00abf3, 0.6);
        [taskButton setTitle:[NSString stringWithFormat:@"今日推荐任务:%@Day%@", task[@"templateCaseName"], task[@"targetDay"]] forState:UIControlStateNormal];
        [taskButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        taskButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
        [taskButton addTarget:self action:@selector(addTaskRecord) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:taskButton];
        
        [task setValue:nil forKey:@"templateCaseName"];
        
        [UIView animateWithDuration:.4 animations:^{
            taskButton.frame = CGRectMake(0, 0, kScreenWidth, 40);
        } completion:^(BOOL finished){
            weakSelf.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
        }];
    } else {
        self.tableView.tableHeaderView = nil;
    }
}

//今日推荐
- (void)addTaskRecord
{
    NSMutableDictionary *task = self.tasksToday[0];
    WCNCareRecordAddVC *vc = [[WCNCareRecordAddVC alloc] initWithPatient:self.patient withWound:self.wound withTask:task type:WCNCareRecordAddVCTypeAdd];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 右上角弹出菜单

- (void)addRecordBtn:(WCButton *)btn
{
    defineWeakSelf;
    if (self.popView) {
        [self.popView hide:^{
            [weakSelf.maskView removeFromSuperview];
        }];
        return;
    }
    
    UIControl *maskView = [[UIControl alloc] initWithFrame:self.view.bounds];
    [maskView addTarget:self action:@selector(closePopView) forControlEvents:UIControlEventTouchUpInside];
    self.maskView = maskView;
    [self.view addSubview:maskView];
    //添加 列表视图
    WCNAddCareRecordSheetsPopView *popView = [[WCNAddCareRecordSheetsPopView alloc] initWithFrame:CGRectMake(kScreenWidth-130-10, 5, 130, 85)];
    
    __weak typeof(popView) weakPopView = popView;
    popView.itemclick = ^(NSInteger index){
        if (index == 0) {
            WCNWoundDetailVC *vc = [[WCNWoundDetailVC alloc] initWith:nil mode:WCNWoundDetailVCModeAdd];
            vc.patient = weakSelf.patient;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        } else if (index == 1) {
           
            WCNCareRecordAddVC *vc = [[WCNCareRecordAddVC alloc] initWithPatient:weakSelf.patient wound:weakSelf.wound type:WCNCareRecordAddVCTypeAdd];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        
        [weakPopView hide:^{
            [weakSelf.maskView removeFromSuperview];
        }];
    };
    self.popView = popView;
    [maskView addSubview:popView];
    
    CGRect frame = [btn convertRect:btn.bounds toView:popView];
    [popView setPoint:CGPointMake(frame.origin.x+frame.size.width/2, 0)];
    
    [popView show:nil];
}

- (void)choiceCase:(WCButton *)btn
{
    WCNCareSchemeListVC *vc = [[WCNCareSchemeListVC alloc] initWithPatient:self.patient];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)closePopView
{
    defineWeakSelf;
    if (self.popView) {
        [self.popView hide:^{
            [weakSelf.maskView removeFromSuperview];
        }];
        return;
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    NSIndexPath *indexPath = objc_getAssociatedObject(alertView, &kAlertInfoObjectKey);
    if (buttonIndex == 0) {
        [self uploadCacheCareAtIndexPath:indexPath];
    } else if (buttonIndex == 1) {
        [self deleteLocalCareRecordByIndex:indexPath];
        [self refreshStepOne:YES];
    }
}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.detail.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //cell的高度 根据有无图片调整
    NSDictionary *timeItem = self.detail[indexPath.row];
    NSArray *imgs = timeItem[@"images"];
    if (imgs.count > 0) {
        return 140;
    } else {
        return 105;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    NSDictionary *timeItem = self.detail[indexPath.row];
    
    NSArray *imgs = timeItem[@"images"];
    //用了两个cell (有图 和 无图片两种)
    if (imgs.count > 0) {
        WCNCareRecordTCell *imgcell = [tableView dequeueReusableCellWithIdentifier:cellId1 forIndexPath:indexPath];
        [imgcell setImgs:imgs];
        cell = imgcell;
    } else {
        WCNCareRecordNoImgTCell *noImgCell = [tableView dequeueReusableCellWithIdentifier:cellId2 forIndexPath:indexPath];
        cell = noImgCell;
    }
    
    UIImageView *typeImgSign = [cell valueForKey:@"typeImgSign"];
    typeImgSign.image = [self signType:timeItem];
    
    UILabel *cellTitle = [cell valueForKey:@"cellTimeTitle"];
    cellTitle.text = timeItem[@"uploadTime"];
    
    UILabel *typeTitle = [cell valueForKey:@"type"];
    typeTitle.text = [self careCaseTitle:timeItem];
    
    UIImageView *nurseAvatarView = [cell valueForKey:@"nurseAvatar"];
    NSString *nurseId = [NSString stringWithFormat:@"%@", timeItem[@"uploadBy"]];
    UIImage *image = [[WCImageManager sharedMg] image:nurseId type:WCImageTypeNurse size:WCImageSizeSmall cache:YES];
    nurseAvatarView.image = image?image:[UIImage imageNamed:@"Nurse_default"];
    [cell setValue:nurseId forKey:@"nurseId"];
    //
    if (![[WCImageManager sharedMg] hasImage:nurseId type:WCImageTypeNurse size:WCImageSizeSmall]) {
        [[WCImageManager sharedMg] downloadImage:nurseId type:WCImageTypeNurse size:WCImageSizeSmall cache:YES success:^(UIImage *image, NSString *stringId){
            if ([stringId isEqualToString:[cell valueForKey:@"nurseId"]]) {
                nurseAvatarView.image = image;
            }
        } failure:nil];
    }
    
        UIButton *commentBtn = [cell valueForKey:@"commentBtn"];
        if (timeItem[@"id"]) {
            
            if (timeItem[@"commentCount"]) {
                if ([timeItem[@"commentCount"] integerValue] ==0) {
                     [commentBtn setImage:[UIImage imageNamed:@"Case_Comment"] forState:UIControlStateNormal];
                }else{
                
                    [commentBtn setImage:[UIImage imageNamed:@"comment_hasNew"] forState:UIControlStateNormal];
                }
            }
            
           
            __weak typeof(self) weakSelf = self;
            void(^showComment)(NSString *) = ^(NSString *comment){
                WCNCareRecordCommentListVC *vc =[WCNCareRecordCommentListVC new];
                vc.recordId = [timeItem[@"id"] integerValue];
                vc.recordType = 1;
                if (weakSelf.navigationController) {
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }else {
                    
                    [weakSelf.delegateNav() pushViewController:vc animated:YES];
                    
                }
            };
            [cell setValue:timeItem[@"comment"] forKey:@"commentStr"];
            [cell setValue:showComment forKey:@"showComment"];

        } else {
            NSArray *imgs = timeItem[@"images"];
            if (imgs.count > 0) {
                WCNCareRecordTCell *imgcell = (WCNCareRecordTCell *)cell;
                [imgcell setImgsFromLocal:imgs];
            }
            
            //缓存在本地，未上传的护理记录
            commentBtn.hidden = NO;
            [commentBtn setImage:[UIImage imageNamed:@"Case_NoSend"] forState:UIControlStateNormal];
            __weak typeof(self) weakSelf = self;
            void(^uploadCacheCare)(id) = ^(id object){
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                    message:nil
                                                                   delegate:weakSelf
                                                          cancelButtonTitle:@"上传"
                                                          otherButtonTitles:@"删除", nil];
                objc_setAssociatedObject(alertView, &kAlertInfoObjectKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
                [alertView show];
            };
            [cell setValue:uploadCacheCare forKey:@"showComment"];
        }
        
        UILabel *dayLabel = [cell valueForKey:@"targetDay"];
        dayLabel.text = [NSString stringWithFormat:@"Day%@", timeItem[@"targetDay"]];
        
        UILabel *summaryLabel = [cell valueForKey:@"summary"];
        summaryLabel.text = [self careCaseContent:timeItem];
        
        UILabel *partLabel = [cell valueForKey:@"part"];
        partLabel.text = [NSString stringWithFormat:@"部位: %@", timeItem[@"bodyPartName"]];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *timeItem = self.detail[indexPath.row];
    if (timeItem[@"id"]) {
        WCNCareRecordAddVC *careRecordVC = [[WCNCareRecordAddVC alloc] initWithData:timeItem type:WCNCareRecordAddVCTypeScan];
        if (self.navigationController) {
            [self.navigationController pushViewController:careRecordVC animated:YES];
        }else {
            
            [self.delegateNav() pushViewController:careRecordVC animated:YES];
        }
//            WCNCareRecordDetailVC *vc = [[WCNCareRecordDetailVC alloc] initWith:timeItem];
//            if (self.navigationController) {
//                [self.navigationController pushViewController:vc animated:YES];
//            }else {
//                
//                [self.delegateNav() pushViewController:vc animated:YES];
//                
//            }
        }else {
            [[WCPopupLayerManager shareMg] showTextOnly:@"该护理记录尚未上传，请在网络良好的情况下点击右上角上传护理记录." withView:self.view];
        }
}

#pragma mark - 长按显示删除提示
- (void)gestureLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint tmpPointTouch = [gestureRecognizer locationInView:self.tableView];
    if (gestureRecognizer.state ==UIGestureRecognizerStateBegan) {
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:tmpPointTouch];
        if (indexPath == nil) {
            NSLog(@"not tableView");
        }else{
            self.longPressIndex = [NSIndexPath indexPathForRow:indexPath.row inSection:0];

            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"修改", @"删除", nil];
            [actionSheet showInView:self.view];
        }
    }
}



- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    NSDictionary *timeItem = self.detail[self.longPressIndex.row];
    if (buttonIndex == 0) {
        WCNCareRecordAddVC *editCareRecordVC = [[WCNCareRecordAddVC alloc] initWithData:timeItem type:WCNCareRecordAddVCTypeEdit];
        if (self.navigationController) {
            [self.navigationController pushViewController:editCareRecordVC animated:YES];
        }else {
            
            [self.delegateNav() pushViewController:editCareRecordVC animated:YES];
        }
        
    }else if (buttonIndex == 1) {
        NSDictionary *param = @{@"id":timeItem[@"id"]};
        NSString *message = @"确定要删除该护理记录？";
        //封装护理记录的参数
        NSString *deleteUrl = kDeleteCareRecord;
        defineWeakSelf;
        [JCAlertView showTwoButtonsWithTitle:@"提示" Message:message ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:nil ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"确定" Click:^{
                //调用服务区接口  删除记录
                
                if (!weakSelf.hud) {
                    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
                    weakSelf.hud = hud;
                }
                
                [[WCNetworkAccessManager sharedMg] POST:deleteUrl parameters:param success:^(NSDictionary *result){
                    [weakSelf.hud setLabelText:result[@"data"]];
                } failure:nil netError:nil always:^{
                    [weakSelf.hud hide:YES afterDelay:1.0];
                    //删除本地对应的数据
                    [weakSelf deleteLocalCacheByIndex:weakSelf.longPressIndex];
                }];
                
        }];
    }
}



#pragma mark - Private

- (UIImage *)signType:(NSDictionary *)data
{
    NSString *type = data[@"type"];
    if ([@"WOUND_ADD_RECORD" isEqualToString:type]) {
        return [UIImage imageNamed:@"CaseCell_BlueHeader"];
    } else if ([@"WOUND_NURSING_RECORD" isEqualToString:type]) {
        return [UIImage imageNamed:@"CaseCell_GreenHeader"];
    } else {
        return [UIImage imageNamed:@"CaseCell_PurpleHeader"];
    }
   
}

- (NSString *)careCaseTitle:(NSDictionary *)data
{
    NSString *type = data[@"type"];
    if ([@"WOUND_ADD_RECORD" isEqualToString:type]) {
        return @"新增伤口记录";
    } else if ([@"WOUND_NURSING_RECORD" isEqualToString:type]) {
        return @"伤口护理记录";
    }
    return @"";
}

- (NSString *)careCaseContent:(NSDictionary *)data
{
    NSArray *medicines = data[@"medicines"];
    if (medicines.count > 0) {
        NSString *desc = @"用药:";
        for (NSDictionary *medicine in medicines) {
            desc = [NSString stringWithFormat:@"%@ %@", desc, medicine[@"name"]];
        }
        return desc;
    }
    
    return @"";
}


- (void)clickTitleView
{
    WCNPatientAddVC *vc = [[WCNPatientAddVC alloc] initWithPatient:self.patient];
    [self.navigationController pushViewController:vc animated:YES];
}

@end
